package com.pcdandan.pcdandan.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pcdandan.pcdandan.config.PcdandanCrawler;
import com.pcdandan.pcdandan.config.token.PcdandanTicket;
import com.pcdandan.pcdandan.entity.XiazhuInfo;
import com.pcdandan.pcdandan.service.dao.XiazhuInfoDao;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class PcdandanService {
	
	@Autowired
	private PcdandanCrawler crawler;
	
	@Autowired
	private XiazhuInfoDao xiazhuInfoDao;
	
	private boolean islogin = false;
	
	private int fail = 0;
	
	private long nextRunTime = 160*1000;
	
	public static String session;
	
	public boolean login(PcdandanTicket ticket) {
		Boolean islogin = (Boolean) crawler.getSubject(ticket).doWork();
		return islogin;
	}
	
	public XiazhuInfo auto(PcdandanTicket ticket) {
		XiazhuInfo xiazhuInfo = (XiazhuInfo) crawler.getSubject(ticket).doWork();
		return xiazhuInfo;
	}
	
	
	private void doWork() {
		PcdandanTicket ticket = new PcdandanTicket();
		ticket.setDomain("pcdandan");
		ticket.setIdentify("me");
		if(!islogin || fail>=3) {
			ticket.setMethod("login");
			islogin = login(ticket);
			if(islogin) {
				fail = 0;
			}
		}
		if(islogin) {
			ticket.setMethod("auto");
			try {
				XiazhuInfo xiazhuInfo = auto(ticket);
				xiazhuInfoDao.save(xiazhuInfo);
				log.info("下注成功，下注期号是:"+xiazhuInfo.getQihao());
				nextRunTime = xiazhuInfo.getJiezhi() + nextRunTime;
			}catch (Exception e) {
				fail++;
			}
		}
	}
	
	public PcdandanService() {
		
	}
	
	class Dutu extends Thread{
		
		@Override
		public void run() {
			while(true) {
				try {
					Thread.sleep(nextRunTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				doWork();
			}
		}
	}
}
